using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Admin_Controls_ServiceManagement : IWS.Lib.Utilities.Web.FormControl
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			this.Initialize();
		}
		this.grdList.ItemCommand += new DataGridCommandEventHandler(grdList_ItemCommand);
	}

	void grdList_ItemCommand(object source, DataGridCommandEventArgs e)
	{
		try
		{
			//itemcommand.
			if (e.CommandName == "Delete")
			{
				Label lblID = e.Item.FindControl("lblID") as Label;
				if (lblID != null)
				{
					if (IWS.Lib.SingleSignOn.Service.Exists(lblID.Text))
					{
						IWS.Lib.SingleSignOn.Service.Remove(lblID.Text);
					}
					this.RefreshData();
				}
			}
			else if (e.CommandName == "Download")
			{
				//write the file, 
				//redir to it. 
				Label lblID = e.Item.FindControl("lblID") as Label;
				if (lblID != null)
				{
					if (IWS.Lib.SingleSignOn.Service.Exists(System.Web.HttpUtility.HtmlDecode(lblID.Text)))
					{
						IWS.Lib.SingleSignOn.Service svc = new IWS.Lib.SingleSignOn.Service(System.Web.HttpUtility.HtmlDecode(lblID.Text));
						string vpath = IWS.Lib.SingleSignOn.SettingCache.GetSetting("KeyFolder");
						string key = System.Web.HttpUtility.HtmlDecode(lblID.Text);

						if (svc.KeyFile == null || svc.KeyFile == string.Empty)
						{
							vpath = System.Web.VirtualPathUtility.Combine(vpath, IWS.Lib.SingleSignOn.Utility.GetRandomString(8) + ".xkey");
							string path = Server.MapPath(vpath);
							while (System.IO.File.Exists(path)) //get a new unique filename.
							{
								vpath = System.Web.VirtualPathUtility.Combine(vpath, IWS.Lib.SingleSignOn.Utility.GetRandomString(8));
								path = Server.MapPath(vpath);
							}

							IWS.Lib.SingleSignOn.MediumTrustSecurity.WriteKeyFile(path, key);
							svc.KeyFile = System.IO.Path.GetFileName(path);
							svc.Save(); //save the new file
						}
						else
						{
							if (svc.KeyFile.Length > 0)
							{
								vpath = System.Web.VirtualPathUtility.Combine(vpath, svc.KeyFile);
								string existing = Server.MapPath(vpath);
								if (!System.IO.File.Exists(existing))
								{
									IWS.Lib.SingleSignOn.MediumTrustSecurity.WriteKeyFile(existing, key);
								}
							}
							else
							{
								throw new ArgumentNullException("KeyFile value does not exist");
							}
						}

						Response.Redirect(vpath);
					}
				}
			}
		}
		catch (Exception ex)
		{
			this.MessageBox1.MessageType = IWS.Lib.Utilities.Web.MessageBox.Type.Error;
			this.MessageBox1.ShowMessage(ex.Message);
		}
	}

	protected override void InitializeCustom()
	{
		this.pnlNew.Visible = false;
		this.RefreshData();
	}

	protected override void OnSaveClick(object sender, EventArgs e)
	{
		try
		{
			if (this.pnlNew.Visible)
			{
				//make sure it doesn't already exist.
				if (!IWS.Lib.SingleSignOn.Service.Exists(lblID.Text))
				{
					IWS.Lib.SingleSignOn.Service svc = new IWS.Lib.SingleSignOn.Service();
					svc.ID = System.Web.HttpUtility.HtmlDecode(lblID.Text);
					DateTime expiration;
					if (DateTime.TryParse(txtExpiration.Text, out expiration))
					{
						svc.ExpirationDate = expiration;
					}
					svc.CreateDate = DateTime.Now.ToUniversalTime();
					svc.Save();
					ResetNewForm();
					this.pnlNew.Visible = false;
					this.RefreshData();
				}
			}
			else
			{
				////perform save on list
				//foreach (DataGridItem item in this.grdList.Items)
				//{
				//   Label lblKey = item.FindControl("lblKey") as Label;
				//   TextBox txtValue = item.FindControl("txtValue") as TextBox;
				//   if (lblKey != null && txtValue != null)
				//   {
				//      IWS.Lib.Ecomm.Setting setting = new IWS.Lib.Ecomm.Setting(lblKey.Text);
				//      setting.ValueX = txtValue.Text;
				//      setting.Save();
				//   }
				//}

				//this.MessageBox1.MessageType = IWS.Lib.Utilities.Web.MessageBox.Type.Normal;
				//this.MessageBox1.ShowMessage("Saved all settings successfully.");


				base.OnSaveClick(sender, e);
			}
		}
		catch (Exception ex)
		{
			IWS.Lib.SingleSignOn.Utility.LogException(System.Reflection.Assembly.GetExecutingAssembly(), ex);
			MessageBox1.ShowMessage(ex.Message);
		}
	}

	protected override void OnBackClick(object sender, EventArgs e)
	{
		if (this.pnlNew.Visible)
		{
			this.pnlNew.Visible = false;
			this.ResetNewForm();
		}
		else
		{
			base.OnBackClick(sender, e);
		}
	}
	private void ResetNewForm()
	{
		this.lblID.Text = "";
		this.txtExpiration.Text = "";
	}
	private void RefreshData()
	{
		this.grdList.DataSource = IWS.Lib.SingleSignOn.Service.ListAll();
		this.grdList.DataBind();
	}
	protected void cmdNew_Click(object sender, EventArgs e)
	{
		pnlNew.Visible = true;
		lblID.Text = System.Web.HttpUtility.HtmlEncode(IWS.Lib.SingleSignOn.Utility.GetRandomUnicodeString(50));
		txtExpiration.Text = DateTime.Now.AddYears(1).ToUniversalTime().ToShortDateString();
	}
}
